import SwiftUI
import AVFoundation
import VideoPlayer
import SlideOverCard

struct VideoPlayView: View {
    @StateObject var videoPlayModel = VideoPlayModel()
    @StateObject var orientationInfo =  OrientationInfo()
    //进度条
    @State private var time: CMTime = .zero
    
    var body: some View {
        VStack{
            if videoPlayModel.urls.count > 0{
                ZStack{
                    //跳转到完成页面
                    NavigationLink(destination: SuccessView(),isActive:$videoPlayModel.complete) {
                        Spacer()
                            .frame(width:0,height: 0)
                    }
                    
                    NavigationLink(
                        destination: RestView(isPresent: $videoPlayModel.restPresent,
                                              preparePresent: $videoPlayModel.preparePresent,
                                              count:videoPlayModel.curAction!.restDuration){
                            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                videoPlayModel.nextAction()
                                videoPlayModel.preparePresent = false
                            }
                           
                        },
                        isActive:$videoPlayModel.restPresent) {
                        Spacer()
                            .frame(width:0,height: 0)
                    }
                        
                    VideoPlayer(url: videoPlayModel.urls[videoPlayModel.curIndex], play: $videoPlayModel.play,time: $time)
                        .onPlayToEndTime {
                            //播放+1
                            if(!videoPlayModel.aVideoComplete){
                                videoPlayModel.curTimes += 1
                                //如果已经到达循环播放的总次数，则换下一个视频或者休息
                                if(videoPlayModel.curTimes >= videoPlayModel.totalTimes){
                                    videoPlayModel.play = false
                                    videoPlayModel.aVideoComplete = true
                                    videoPlayModel.nextActionOrRest()
                                }
                            }
                        }
                        .autoReplay(true)
                        .onStateChanged { state in
                            switch state {
                                case .playing(let totalDuration):
                                    let aVideoDuration = totalDuration
                                    videoPlayModel.aVideoDuration = aVideoDuration
                                    videoPlayModel.totalDuration = aVideoDuration * Double(videoPlayModel.totalTimes)
                                    break
                                case .error(let error):
                                    print("error=\(error)")
                                    break;
                                case _:
                                    break;
                            }
                        }
                        .onChange(of: time){ value in
                            if(videoPlayModel.aVideoComplete) {
                                return
                            }
                            
                            let alPlay = value.seconds + Double(videoPlayModel.curTimes) * videoPlayModel.aVideoDuration
                            videoPlayModel.per = alPlay/videoPlayModel.totalDuration
                        
                            if((alPlay + 5 >= videoPlayModel.totalDuration) && videoPlayModel.hasNotSetTip){
                                videoPlayModel.tipBtn = true
                                videoPlayModel.hasNotSetTip = false
                            }
                            
                        }
                        .aspectRatio(contentMode: .fill)
                        .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: .infinity, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealHeight: .infinity, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                        .onDisappear {
                            videoPlayModel.play = false
                        }
                    VideoPlayInfo(orientation: $orientationInfo.orientation)
                        .padding(.top,20)
                    VideoControl(orientation: $orientationInfo.orientation)
                        .padding(.top,20)
                        .padding(.horizontal,12)
                    
                    if(videoPlayModel.preparePresent){
                        PrepareView(nAction: $videoPlayModel.nAction)
                    }
                    
                }
                .environmentObject(videoPlayModel)
                .ignoresSafeArea(.all)
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            }else{
                loadingIndicator()
            }
        }.onAppear(){
            videoPlayModel.fetchVideoList()
            videoPlayModel.actionDetailModel.fetchActionDataBycid()
        }
        .slideOverCard(isPresented: $videoPlayModel.isPresented, dragEnabled: $videoPlayModel.dragEnabled) {
            ActionDetailView(detailViewModel: videoPlayModel.actionDetailModel)
        }
    }
}

func timeStrToSeconds(s:String) -> Int {
    let strList = s.split(separator: ":")
    let s = Int(strList[2])!
    let m = Int(strList[1])!
    let h = Int(strList[0])!
    let result = s + m * 60 + h * 3600
    return result
}

